#coding=utf-8
from uliweb import expose, decorators
from uliweb.orm import get_model

@expose('/forum_tops')
def index():
    from uliweb import json
    
    Topic = get_model('forumtopic')
    t = []
    for row in Topic.filter(Topic.c.homepage==True).limit(10).order_by(Topic.c.created_on.desc()):
        t.append({'subject':row.subject, 'id':row.id, 'posted_by':row.posted_by.username,
            'created_on':row.created_on.strftime('%Y-%m-%d'), 'forum':row._forum_})
    return json({'rows':t})

@expose('/portal/links')
class LinksView(object):
    def __init__(self):
        self.model = get_model('link')
    
    @expose('')
    def links(self):
        from uliweb import json
        
        t = []
        for row in self.model.all().order_by(self.model.c.order):
            t.append({'name':row.name, 'id':row.id, 'link':row.link,
                'desc':row.desc})
        return json({'rows':t})

    @decorators.check_role('superuser')
    def admin(self):
        """
        显示管理页面
        """
        from uliweb.utils.generic import ListView
        
        pageno = int(request.values.get('page', 1)) - 1
        rows_per_page=int(request.values.get('rows', 10))
        
        def action(value, obj):
            return '<a href="%s">%s</a> <a href="%s" onclick="return confirm(\'确定要删除当前板块吗？\');">%s</a>' % (url_for(self.__class__.edit, id=obj.id), '编辑', url_for(self.__class__.delete, id=obj.id), '删除')

        view = ListView(self.model, rows_per_page=rows_per_page, pageno=pageno,
            fields_convert_map={'action':action})
        if 'data' in request.values:
            return json(view.json())
        else:
            result = view.run(head=True, body=False)
            result.update({'table':view})
            return result
        
    @decorators.check_role('superuser')
    def add(self):
        """
        添加新的板块
        """
        from uliweb.utils.generic import AddView
        
        view = AddView(self.model, url_for(self.__class__.admin))
        return view.run()
    
    @expose('category_edit/<id>')
    @decorators.check_role('superuser')
    def edit(self, id):
        """
        修改板块
        """
        from uliweb.utils.generic import EditView
        
        obj = self.model.get(int(id))
        
        view = EditView(self.model, url_for(self.__class__.admin), obj=obj)
        return view.run()
    
    @expose('category_delete/<id>')
    @decorators.check_role('superuser')
    def delete(self, id):
        """
        删除板块
        """
        from uliweb.utils.generic import DeleteView
        
        obj = self.model.get(int(id))
        
        view = DeleteView(self.model, url_for(self.__class__.admin), 
            url_for(self.__class__.admin),
            obj=obj)
        return view.run()
    
